#!/bin/bash

# 获取公共配置参数PATTERN
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/config.sh"

echo "获取本地分支..."
local_branches=$(git for-each-ref --format='%(refname:short)' refs/heads)

echo "获取远程分支..."
remote_branches=$(
  git for-each-ref --format='%(refname:short)' refs/remotes | grep -vE '^origin/HEAD$|^origin$'
)

invalid_local=()
invalid_remote=()

# 检查本地分支
for branch in $local_branches; do
  if ! [[ $branch =~ $PATTERN ]]; then
    invalid_local+=("$branch")
  fi
done

# 检查远程分支
for branch in $remote_branches; do
  # 去掉前缀 origin/
  short_branch=${branch#origin/}
  if ! [[ $short_branch =~ $PATTERN ]]; then
    invalid_remote+=("$short_branch")
  fi
done

# 显示所有不符合命名规范的分支
echo "以下分支不符合命名规范："
if [ ${#invalid_local[@]} -eq 0 ] && [ ${#invalid_remote[@]} -eq 0 ]; then
  echo "✔ 所有分支命名都符合规范。"
  exit 0
fi

if [ ${#invalid_local[@]} -gt 0 ]; then
  echo "本地分支："
  for b in "${invalid_local[@]}"; do
    echo "  $b"
  done
fi

if [ ${#invalid_remote[@]} -gt 0 ]; then
  echo "远程分支："
  for b in "${invalid_remote[@]}"; do
    echo "  origin/$b"
  done
fi

# 用户确认是否删除
read -p "是否删除以上分支？输入 y 继续删除，其他键退出： " confirm
if [[ $confirm != "y" ]]; then
  echo "已取消删除操作。"
  exit 0
fi

# 删除本地分支
for b in "${invalid_local[@]}"; do
  echo "删除本地分支 $b"
  git branch -D "$b"
done

# 删除远程分支
for b in "${invalid_remote[@]}"; do
  echo "删除远程分支 origin/$b"
  git push origin --delete "$b"
done

echo "✅ 分支清理完成。"
